package com.cositas.dulces.lp.promo2012.utils;

import java.util.Collection;
import java.util.List;

import com.cositas.dulces.lp.promo2012.dbentities.Choice;
import com.cositas.dulces.lp.promo2012.dbentities.Participant;
import com.cositas.dulces.lp.promo2012.dbentities.Question;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

public class PromotionUtils {

	public static Entity getParticipant(Key k) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		try {
			Entity entity = datastore.get(k);
			return entity;
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public static String[] existsQuestion(String fbid) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query(Question.entity_name);
		List<Entity> greetings = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10000));
		for (Entity q : greetings) {
			String reminder = (String)q.getProperty(Question.field_remainder);
			Integer r = Integer.valueOf(reminder);
			if (r > 0) {
				Collection<String> col = (Collection<String>)q.getProperty(Question.field_fbids);
				if (col == null || !col.contains(fbid)) {
					return new String[] {q.getKey().getName().toString(), (String)q.getProperty(Question.field_question)};
				}
			}
		}
		return null;
	}
	
	public static String hasVoted(String fbid, String opt) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Key wallShareKey = KeyFactory.createKey(Choice.entity_name, fbid + "-" + opt);
		try {
			Entity wallShare = datastore.get(wallShareKey);
			return (String)wallShare.getProperty(Choice.field_choice);
		} catch (EntityNotFoundException e) {
			return null;
		}
	}
	
	public static String getPoints(Entity entity) {
		return entity.getProperty(Participant.field_points).toString();
	}
}
